package com.yiduo.outpost.ucenter.security;

import com.yiduo.outpost.core.security.TokenProvider;
import com.yiduo.outpost.core.security.jwt.JwtProperties;
import com.yiduo.outpost.core.model.entity.User;
import com.yiduo.outpost.ucenter.service.UserService;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Component;

@Slf4j
@Component
public class JwtTokenProvider implements TokenProvider {

    @Autowired
    private JwtProperties jwtProperties;

    @Autowired
    private UserService userService;

    @Override
    public Authentication getAuthentication(String token) {
        Claims claims = Jwts.parserBuilder()
            .setSigningKey(jwtProperties.getKey())
            .build()
            .parseClaimsJws(token)
            .getBody();

        Long uid = claims.get(USER_ID_KEY, Long.class);
        User user = userService.getUserWithPermissions(uid);
        return new UsernamePasswordAuthenticationToken(user, token, user.getAuthorities());
    }

    @Override
    public boolean validateToken(String authToken) {
        try {
            Jwts.parserBuilder().setSigningKey(jwtProperties.getKey()).build()
                .parseClaimsJws(authToken);
            return true;
        } catch (Exception e) {
            log.debug("Invalid JWT token: {}. {}", authToken, e);
            return false;
        }
    }

}
